#

| Chapter 26 |

# 26. Regular Expressions (Pattern Matching)

Contents:
That's an Expression
Don't Confuse Regular Expressions with Wildcards
Understanding Expressions
Using Metacharacters in Regular Expressions
Getting Regular Expressions Right
Just What Does a Regular Expression Match?
Limiting the Extent of a Match
I Never Meta Character I Didn't Like
Valid Metacharacters for Different UNIX Programs
Pattern Matching Quick Reference with Examples

## 26.1 That's an Expression

When my young daughter is struggling to understand the meaning of an idiomatic expression, such as, "Someone let the cat out of the bag," before I tell her what it means, I have to tell her that it's an expression, that she's not to interpret it literally. (As a consequence, she also uses "That's just an expression" to qualify her own remarks, especially when she is unsure about what she has just said.)

An expression, even in computer terminology, is not something to be interpreted literally. It is something that needs to be evaluated.

Many UNIX programs use a special "regular expression syntax" for specifying what you could think of as "wildcard searches" through files. Regular expressions describe patterns, or sequences of characters, without necessarily specifying the characters literally. You'll also hear this process referred to as "pattern matching."

In this chapter, we depart a bit from the usual "tips and tricks" style of the book to provide an extended tutorial about regular expressions in article 26.4. We did this because regular expressions are so important to many of the tips and tricks elsewhere in the book, and we wanted to make sure that they are covered thoroughly.

This tutorial article is accompanied by a few snippets of advice (articles 26.5 and 26.7), and a few tools that help you see what your expressions are matching (article 26.6). There's also a quick reference (article 26.10) for those of you who just need a refresher.

For tips, tricks and tools that rely on an understanding of regular expression syntax, you have only to look at:

- Chapter 27, Searching Through Files, Searching Through Files

- Chapter 30, vi Tips and Tricks, vi Tips and Tricks

- Chapter 33, Batch Editing, Batch Editing

- Chapter 34, The sed Stream Editor, The sed Stream Editor

- Chapter 37, Perl, a Pathologically Eclectic Rubbish Lister, Perl, A Pathologically Eclectic Rubbish Lister

O'Reilly's Mastering Regular Expressions, by Jeffrey Friedl, is a gold mine of examples and specifics.

- DD, TOR (Dale wrote the good part, in O'Reilly & Associates' sed & awk)

25.21 Numbering Lines |  | 26.2 Don't Confuse Regular Expressions with Wildcards